<template>
  <div class="app-container">
    <el-form :model="questionForm" :rules="rules" ref="questionFormRef" label-width="100px">
      <!-- 所属章节选择 -->
      <el-form-item label="所属章节" prop="chapterId" required>
        <el-tree-select
          v-model="questionForm.chapterId"
          :data="chapterOptions"
          :props="{ value: 'chapterId', label: 'chapterName', children: 'children' }"
          value-key="chapterId"
          placeholder="请选择所属章节"
          check-strictly
        />
      </el-form-item>
      
      <!-- 题干 -->
      <el-form-item label="题干" prop="questionContent" required>
        <div class="content-box" @click="openEditor('questionContent')">
          <div v-if="questionForm.questionContent" v-html="questionForm.questionContent" class="content-html"></div>
          <div v-else class="placeholder-text">点击编辑题干内容</div>
        </div>
      </el-form-item>
      
      <!-- 标准答案 -->
      <el-form-item label="标准答案" prop="answer" required>
        <div class="content-box" @click="openEditor('answer')">
          <div v-if="questionForm.answer" v-html="questionForm.answer" class="content-html"></div>
          <div v-else class="placeholder-text">点击编辑标准答案</div>
        </div>
      </el-form-item>
      
      <!-- 分值 -->
      <el-form-item label="分值" prop="score" required>
        <el-input-number
          v-model="questionForm.score"
          :min="0.5"
          :max="20"
          :step="0.5"
          step-strictly
        />
      </el-form-item>
      
      <!-- 难度 -->
      <el-form-item label="难度" prop="difficulty" required>
        <el-rate
          v-model="questionForm.difficulty"
          :max="5"
          :texts="['简单', '较简单', '中等', '较难', '困难']"
          show-text
        />
      </el-form-item>

      <!-- 状态（仅编辑模式显示） -->
      <el-form-item label="状态" prop="status" v-if="isEdit">
        <el-radio-group v-model="questionForm.status">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 解析 -->
      <el-form-item label="解析" prop="analysis">
        <div class="content-box" @click="openEditor('analysis')">
          <div v-if="questionForm.analysis" v-html="questionForm.analysis" class="content-html"></div>
          <div v-else class="placeholder-text">点击编辑解析内容</div>
        </div>
      </el-form-item>
      
      <!-- 底部按钮 -->
      <el-form-item class="button-group">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button 
          type="info" 
          icon="View" 
          @click="previewQuestion"
        >预览</el-button>
        <el-button 
          type="warning" 
          icon="ChatDotRound" 
          @click="openAIAssistant"
        >AI辅助</el-button>
      </el-form-item>
    </el-form>

    <!-- 富文本编辑器对话框 -->
    <el-dialog
      v-model="editorVisible"
      title="内容编辑"
      width="800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="editor-container">
        <QuillEditor
          v-model:content="tempContent"
          content-type="html"
          theme="snow"
          toolbar="full"
          :options="editorOptions"
          ref="quillEditor"
        />
        <div class="image-tip"><p>提示：使用 $...$ 插入行内公式
          使用 $$...$$ 插入块级公式</p><p>提示：图片会自动限制大小，过大的图片将被等比例缩放</p></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmEdit">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="题目预览"
      width="600px"
      append-to-body
      @opened="renderMathInPreview" 
    >
      <div class="preview-container" ref="previewContainer">
        <div class="preview-title">题干:</div>
        <div class="preview-content content-html" v-html="processedQuestionContent"></div>
        
        <div class="preview-title">标准答案:</div>
        <div class="preview-content content-html" v-html="questionForm.answer"></div>
        
        <div v-if="questionForm.analysis" class="preview-title">解析:</div>
        <div v-if="questionForm.analysis" class="preview-content content-html" v-html="processedAnalysis"></div>
      </div>
    </el-dialog>

    <!-- AI辅助对话框 -->
    <el-dialog
      v-model="aiDialogVisible"
      title="AI辅助出题"
      width="800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      @close="handleAIDialogClose"
    >
      <div class="ai-container">
        <div class="ai-content" ref="aiContentRef">
          <div v-if="aiMessages.length === 0" class="ai-empty-message">
            <p>欢迎使用AI辅助出题功能！</p>
            <p>您可以：</p>
            <ul>
              <li>生成一道关于当前章节的简答题</li>
              <li>修改/完善当前编辑的题目</li>
              <li>针对特定知识点提问</li>
            </ul>
          </div>
          <div v-else class="ai-messages">
            <div v-for="(msg, idx) in aiMessages" :key="idx" :class="['ai-message', msg.role]">
              <div class="ai-message-content" v-html="msg.content"></div>
            </div>
          </div>
        </div>
        <div class="ai-input-area">
          <el-input
            v-model="aiPrompt"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题或需求..."
            @keydown.enter.ctrl.prevent="sendAIMessage"
          ></el-input>
        </div>
        <div class="ai-function-buttons">
          <el-tooltip content="直接生成题目" placement="top">
            <el-button type="primary" @click="generateQuestionWithAI" :loading="aiLoading">生成题目</el-button>
          </el-tooltip>
          <el-tooltip content="仅编辑已有题目时可用" placement="top">
            <el-button type="success" @click="optimizeQuestionWithAI" :loading="aiLoading" :disabled="!canOptimizeQuestion">优化题目</el-button>
          </el-tooltip>
          <el-tooltip content="分析当前题目" placement="top">
            <el-button type="info" @click="analyzeCurrentQuestion" :loading="aiLoading" :disabled="!isValidQuestion">分析题目</el-button>
          </el-tooltip>
          <el-tooltip content="获取改进建议" placement="top">
            <el-button type="warning" @click="getImprovementSuggestion" :loading="aiLoading" :disabled="!questionForm.questionId">改进建议</el-button>
          </el-tooltip>
          <el-tooltip content="测试AI API" placement="top">
            <el-button type="danger" @click="testAIApi" :loading="aiLoading">测试API</el-button>
          </el-tooltip>
        </div>
        <div class="ai-action-buttons">
          <el-button @click="sendAIMessage" :loading="aiLoading">发送</el-button>
          <el-button type="warning" @click="applyAIGeneratedContent" :disabled="!isContentApplicable">应用</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { listChapter } from '@/api/manage/chapter';
import { addQuestion, getQuestion, updateQuestion } from '@/api/manage/question';
import { 
  generateQuestion, 
  optimizeQuestion, 
  chatWithAI, 
  analyzeGeneratedQuestion, 
  generateQuestionSuggestion,
  testAIConnection
} from '@/api/manage/ai';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

// 路由相关
const route = useRoute();
const router = useRouter();

// 判断是否为编辑模式
const isEdit = ref(false);

// 生成唯一ID的函数
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
};

// 表单数据
const questionForm = ref({
  questionId: '',
  questionType: 4, // 简答题类型为4
  questionContent: '',
  chapterId: null,
  difficulty: 3,
  answer: '',
  score: 5, // 简答题默认分值调整为5分
  analysis: '',
  status: 0
});

// 章节数据
const chapterOptions = ref([]);

// 表单校验规则
const rules = {
  chapterId: [{ required: true, message: '请选择所属章节', trigger: 'change' }],
  questionContent: [{ required: true, message: '请输入题干内容', trigger: 'blur' }],
  answer: [{ required: true, message: '请输入标准答案', trigger: 'blur' }],
  score: [{ required: true, message: '请设置分值', trigger: 'blur' }],
  difficulty: [{ required: true, message: '请设置难度', trigger: 'change' }]
};

// 表单引用
const questionFormRef = ref(null);
const quillEditor = ref(null);

// 编辑器相关变量
const editorVisible = ref(false);
const tempContent = ref('');
const currentEditField = ref('');

// 预览对话框
const previewVisible = ref(false);

// AI辅助对话框
const aiDialogVisible = ref(false);
const aiContentRef = ref(null);
const aiMessages = ref([]);
const aiPrompt = ref('');
const aiLoading = ref(false);
const aiGeneratedContent = ref(null);
// 跟踪AI最近操作类型，用于判断内容是否可应用
const aiLastAction = ref('');
const isContentApplicable = computed(() => {
  // 只有生成题目操作的内容可以应用
  return aiGeneratedContent.value !== null && aiLastAction.value === 'generate';
});
const isValidQuestion = computed(() => {
  return questionForm.value.questionContent.trim() !== '' && 
         questionForm.value.answer.trim() !== '';
});

// 添加表示当前题目是否可优化的计算属性
const canOptimizeQuestion = computed(() => {
  return isEdit.value && 
         questionForm.value.questionId && 
         isValidQuestion.value;
});

// 获取难度文本描述
const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    1: '简单',
    2: '较简单',
    3: '中等',
    4: '较难',
    5: '困难'
  };
  return difficultyMap[difficulty] || '中等';
};

// 处理图片大小的函数
const processImageSize = (html) => {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  const images = tempDiv.querySelectorAll('img');
  images.forEach(img => {
    img.style.maxWidth = '100%';
    img.style.height = 'auto';
    img.style.objectFit = 'contain';
  });
  return tempDiv.innerHTML;
};

// Quill编辑器配置
const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'script': 'sub' }, { 'script': 'super' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image']
    ],
    imageUploader: {
      upload: file => {
        return new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('file', file);
          
          fetch('/dev-api/common/upload', {
            method: 'POST',
            body: formData
          })
            .then(response => response.json())
            .then(result => {
              if (result.code === 200 && result.data) {
                resolve(result.data.url);
              } else {
                reject('上传失败: ' + (result.msg || '未知错误'));
              }
            })
            .catch(error => {
              reject('上传出错: ' + error.message);
            });
        });
      }
    }
  },
  placeholder: '请输入内容...'
};

// 获取章节树
const getChapterTreeselect = () => {
  listChapter().then(response => {
    const data = { chapterId: 0, chapterName: '离散数学', children: [] };
    data.children = handleTree(response.data, "chapterId", "parentId");
    chapterOptions.value = [data];
  });
};

// 处理树形结构
const handleTree = (data, id, parentId) => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
};

// 打开编辑器对话框
const openEditor = (field) => {
  currentEditField.value = field;
  tempContent.value = '';
  
  nextTick(() => {
    if (field === 'questionContent') {
      tempContent.value = questionForm.value.questionContent || '';
    } else if (field === 'analysis') {
      tempContent.value = questionForm.value.analysis || '';
    } else if (field === 'answer') {
      tempContent.value = questionForm.value.answer || '';
    }
    
    editorVisible.value = true;
    
    nextTick(() => {
      if (quillEditor.value) {
        quillEditor.value.focus();
      }
    });
  });
};

// 确认编辑
const confirmEdit = () => {
  const processedContent = processImageSize(tempContent.value);
  
  if (currentEditField.value === 'questionContent') {
    questionForm.value.questionContent = processedContent;
  } else if (currentEditField.value === 'analysis') {
    questionForm.value.analysis = processedContent;
  } else if (currentEditField.value === 'answer') {
    questionForm.value.answer = processedContent;
  }
  
  editorVisible.value = false;
};

// 取消编辑
const cancelEdit = () => {
  editorVisible.value = false;
  tempContent.value = '';
};

// 预览题目
const previewQuestion = () => {
  if (!questionForm.value.questionContent) {
    ElMessage.warning('请先填写题干内容');
    return;
  }
  previewVisible.value = true;
};

// 重置表单
const resetForm = () => {
  questionFormRef.value.resetFields();
  questionForm.value.questionContent = '';
  questionForm.value.answer = '';
  questionForm.value.analysis = '';
};

// 提交表单
const submitForm = () => {
  questionFormRef.value.validate(valid => {
    if (valid) {
      const submitData = {
        questionId: questionForm.value.questionId || generateId(),
        questionType: 4, // 简答题类型
        questionContent: questionForm.value.questionContent,
        chapterId: questionForm.value.chapterId,
        difficulty: questionForm.value.difficulty,
        answer: questionForm.value.answer,
        score: questionForm.value.score,
        analysis: questionForm.value.analysis,
        status: questionForm.value.status
      };
      
      if (isEdit.value) {
        updateQuestion(submitData).then(response => {
          ElMessage.success('修改成功');
          router.push({ path: '/question/question' });
        });
      } else {
        submitData.status = 0;
        addQuestion(submitData).then(response => {
          ElMessage.success('保存成功');
          router.push({ path: '/question/question' });
        });
      }
    }
  });
};

// 获取题目详情
const getDetail = (questionId) => {
  getQuestion(questionId).then(response => {
    const questionData = response.data;
    questionForm.value = {
      questionId: questionData.questionId,
      questionType: questionData.questionType,
      questionContent: questionData.questionContent,
      chapterId: questionData.chapterId,
      difficulty: questionData.difficulty,
      answer: questionData.answer,
      score: questionData.score,
      analysis: questionData.analysis,
      status: questionData.status
    };
  });
};

// 修改MathJax加载方式
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      // 如果已经加载，重新配置并尝试渲染
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
    };
    document.head.appendChild(script);
  });
};

// 处理数学公式的函数
const processMathContent = (html) => {
  // 直接返回内容，由MathJax处理
  return html;
};

// 为预览准备的处理后内容
const processedQuestionContent = computed(() => {
  return processMathContent(questionForm.value.questionContent || '');
});

const processedOptions = computed(() => {
  return questionForm.value.options.map(option => ({
    ...option,
    optionContent: processMathContent(option.optionContent || '')
  }));
});

const processedAnalysis = computed(() => {
  return processMathContent(questionForm.value.analysis || '');
});

// 优化渲染函数，添加更多日志和重试机制
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 作为备选方案，使用KaTeX尝试渲染
    try {
      if (!window.katex) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css';
        document.head.appendChild(link);
        
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.js';
        script.onload = () => {
          const autoRenderScript = document.createElement('script');
          autoRenderScript.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/contrib/auto-render.min.js';
          autoRenderScript.onload = () => {
            window.renderMathInElement(previewContainer.value, {
              delimiters: [
                {left: '$$', right: '$$', display: true},
                {left: '$', right: '$', display: false}
              ]
            });
          };
          document.head.appendChild(autoRenderScript);
        };
        document.head.appendChild(script);
      } else {
        window.renderMathInElement(previewContainer.value, {
          delimiters: [
            {left: '$$', right: '$$', display: true},
            {left: '$', right: '$', display: false}
          ]
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// 打开AI助手对话框
const openAIAssistant = () => {
  aiDialogVisible.value = true;
  // 初始化消息，如果为空的话
  if (aiMessages.value.length === 0) {
    aiMessages.value.push({
      role: 'assistant',
      content: '你好！我是AI助手，可以帮你创建或优化简答题。请告诉我你的需求。'
    });
  }
  nextTick(() => {
    if (aiContentRef.value) {
      aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
    }
  });
};

// 处理AI对话框关闭事件
const handleAIDialogClose = () => {
  // 清空生成内容和重置状态
  aiPrompt.value = '';
  aiGeneratedContent.value = null;
  aiLastAction.value = '';
  // 保留历史消息，但限制数量
  if (aiMessages.value.length > 10) {
    aiMessages.value = aiMessages.value.slice(-10);
  }
};

// 发送AI消息
const sendAIMessage = async () => {
  if (!aiPrompt.value.trim()) {
    ElMessage.warning('请输入您要发送的消息');
    return;
  }
  
  try {
    aiLoading.value = true;
    
    // 构建历史消息数组
    const historyMessages = [];
    for (const msg of aiMessages.value) {
      historyMessages.push(msg.content.replace(/<br>/g, '\n'));
    }
    
    // 加入当前消息
    aiMessages.value.push({ role: 'user', content: aiPrompt.value });
    
    // 清空输入框
    const currentPrompt = aiPrompt.value;
    aiPrompt.value = '';
    
    // 调用AI API
    const response = await chatWithAI(historyMessages, currentPrompt);
    
    console.log('AI聊天响应:', response);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 尝试从响应中解析结构化题目（如果有的话）
      if (response.data.questionContent || (response.data.content && response.data.content.includes('题干') && response.data.content.includes('答案'))) {
        console.log('检测到可能包含完整题目的响应，尝试解析');
        const parsedQuestion = parseQuestionFromText(response.data.content);
        if (parsedQuestion) {
          console.log('成功解析出题目结构:', parsedQuestion);
          aiGeneratedContent.value = parsedQuestion;
          aiLastAction.value = 'generate';
        }
      } else {
        // 清除可应用内容，因为普通聊天不包含可应用的题目
        aiGeneratedContent.value = null;
        aiLastAction.value = 'chat';
      }
    }
  } catch (error) {
    console.error('AI聊天出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，处理您的请求失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 渲染AI消息中的数学公式
const renderAIMessageMath = async () => {
  await nextTick();
  try {
    // 首先处理数字后跟逗号和下划线的格式
    const mathElements = document.querySelectorAll('.ai-message.assistant');
    if (mathElements.length > 0) {
      for (const el of mathElements) {
        // 替换所有数字后跟逗号和下划线的模式
        const originalHtml = el.innerHTML;
        const fixedHtml = originalHtml.replace(/(\d),(_+)/g, (match, digit, underscores) => {
          console.log(`AI消息中修复填空格式: 替换 "${match}" 为 "${underscores}"`);
          return underscores;
        });
        
        if (originalHtml !== fixedHtml) {
          el.innerHTML = fixedHtml;
        }
      }
    }
    
    if (window.MathJax) {
      await loadMathJax();
      if (mathElements.length > 0) {
        if (window.MathJax.typesetPromise) {
          await window.MathJax.typesetPromise(mathElements);
          console.log('AI消息公式渲染完成');
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset(mathElements);
          console.log('AI消息公式渲染完成');
        }
      }
    }
  } catch (e) {
    console.error('渲染AI消息中的公式出错:', e);
  }
};

// 通过AI生成题目
const generateQuestionWithAI = async () => {
  try {
    aiLoading.value = true;
    aiPrompt.value = '';
    const promptText = `请帮我创建一道关于${questionForm.value.chapterId ? chapterOptions.value[0].children.find(c => c.chapterId === questionForm.value.chapterId)?.chapterName || '离散数学' : '离散数学'}的${getDifficultyText(questionForm.value.difficulty)}的简答题，请提供完整的题干、标准答案和详细解析。`;
    
    aiMessages.value.push({ role: 'user', content: promptText });
    
    const response = await generateQuestion(
      questionForm.value.chapterId || '', 
      4, // 简答题类型为4
      questionForm.value.difficulty, 
      promptText,
      0 // 简答题不需要选项
    );
    
    console.log('AI生成题目响应:', response);
    
    if (response && response.data) {
      const content = response.data.content;
      if (content) {
        // 显示AI返回的完整内容
        aiMessages.value.push({ 
          role: 'assistant', 
          content: content.replace(/\n/g, '<br>') 
        });
        
        // 标记最后操作类型为生成
        aiLastAction.value = 'generate';
        
        // 创建结构化题目数据对象
        let structuredQuestionData = {
          content: content // 保留原始完整内容
        };
        
        // 首先尝试通过我们自己的解析器解析内容
        const parsedQuestion = parseQuestionFromText(content);
        if (parsedQuestion && parsedQuestion.questionContent && parsedQuestion.answer) {
          console.log('成功通过前端解析器解析题目:', parsedQuestion);
          structuredQuestionData = {
            ...structuredQuestionData,
            ...parsedQuestion
          };
        } 
        // 如果前端解析失败但后端提供了结构化数据，则使用后端数据
        else if (response.data.questionContent || response.data.answer) {
          console.log('使用后端提供的结构化数据');
          
          // 清理后端返回的题干内容
          if (response.data.questionContent) {
            let cleanedQuestionContent = response.data.questionContent
              .replace(/^以下是一道关于[^"]*的[^"]*题：\s*/i, '')
              .replace(/^这是一道关于[^"]*的[^"]*题：\s*/i, '')
              .replace(/^###\s*题目\s*/i, '') // 移除"### 题目"标记
              .replace(/^###\s*题干\s*/i, '') // 移除"### 题干"标记
              .trim();
            
            structuredQuestionData.questionContent = cleanedQuestionContent;
          }
          
          // 添加答案
          if (response.data.answer) {
            // 清理可能的前缀
            let cleanedAnswer = response.data.answer
              .replace(/^(?:参考)?\s*答案[:：]\s*/i, '')
              .trim();
            
            structuredQuestionData.answer = cleanedAnswer;
          }
          
          // 添加解析
          if (response.data.analysis) {
            // 清理可能的前缀
            let cleanedAnalysis = response.data.analysis
              .replace(/^解析[:：]\s*/i, '')
              .trim();
            
            structuredQuestionData.analysis = cleanedAnalysis;
          }
        }
        
        console.log('处理后的结构化题目数据:', structuredQuestionData);
        aiGeneratedContent.value = structuredQuestionData;
      }
    }
  } catch (error) {
    console.error('AI生成题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，生成题目失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 通过AI优化现有题目
const optimizeQuestionWithAI = async () => {
  try {
    if (!isValidQuestion.value) {
      ElMessage.warning('请先完成题目基本内容再进行优化');
      return;
    }
    
    aiLoading.value = true;
    aiPrompt.value = '';
    
    const prompt = '请优化这道简答题，使表述更清晰，难度更适中，并增强教学价值。';
    
    aiMessages.value.push({ role: 'user', content: prompt });
    
    const questionData = {
      questionId: questionForm.value.questionId,
      questionType: 4, // 简答题
      questionContent: questionForm.value.questionContent,
      chapterId: questionForm.value.chapterId,
      difficulty: questionForm.value.difficulty,
      answer: questionForm.value.answer,
      analysis: questionForm.value.analysis
    };
    
    // 调用AI API优化题目 - 修正传参方式
    const response = await optimizeQuestion(questionForm.value.questionId, prompt, questionForm.value.difficulty);
    
    console.log('AI优化题目响应:', response);
    
    if (response && response.data) {
      const content = response.data.content;
      if (content) {
        aiMessages.value.push({ 
          role: 'assistant', 
          content: content.replace(/\n/g, '<br>') 
        });
        
        // 标记最后操作类型为优化
        aiLastAction.value = 'optimize';
        
        // 解析优化后的题目
        const optimizedQuestion = parseQuestionFromText(content);
        if (optimizedQuestion) {
          console.log('成功解析出优化后的题目结构:', optimizedQuestion);
          aiGeneratedContent.value = optimizedQuestion;
        } else if (response.data.questionContent) {
          // 如果解析失败但API返回了结构化数据，使用API返回的数据
          aiGeneratedContent.value = {
            content: content,
            questionContent: response.data.questionContent,
            answer: response.data.answer,
            analysis: response.data.analysis
          };
        }
      }
    }
  } catch (error) {
    console.error('AI优化题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，优化题目失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 分析当前题目
const analyzeCurrentQuestion = async () => {
  try {
    if (!isValidQuestion.value) {
      ElMessage.warning('请先完成题目基本内容再进行分析');
      return;
    }
    
    aiLoading.value = true;
    
    const questionData = {
      questionId: questionForm.value.questionId,
      questionType: 4, // 简答题
      questionContent: questionForm.value.questionContent,
      chapterId: questionForm.value.chapterId,
      difficulty: questionForm.value.difficulty,
      answer: questionForm.value.answer,
      analysis: questionForm.value.analysis
    };
    
    // 构建分析提示并添加到消息列表
    const prompt = `请分析这道简答题的质量、难度和教学价值。`;
    aiMessages.value.push({ role: 'user', content: prompt });
    
    // 调用API分析题目
    const response = await analyzeGeneratedQuestion(questionData);
    
    console.log('AI分析题目响应:', response);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 标记最后操作类型为分析
      aiLastAction.value = 'analyze';
      // 清除可应用内容，因为分析内容不需要应用
      aiGeneratedContent.value = null;
    }
  } catch (error) {
    console.error('AI分析题目出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，分析题目失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 获取改进建议
const getImprovementSuggestion = async () => {
  try {
    if (!questionForm.value.questionId) {
      ElMessage.warning('请先创建或加载一个题目再获取改进建议');
      return;
    }
    
    aiLoading.value = true;
    
    // 构建提示信息并添加到消息列表
    const prompt = `请为这道简答题提供改进建议，包括如何提高题目质量、如何调整难度以及如何增强教学价值。`;
    aiMessages.value.push({ role: 'user', content: prompt });
    
    // 调用API获取改进建议
    const response = await generateQuestionSuggestion(questionForm.value.questionId);
    
    console.log('AI改进建议响应:', response);
    
    if (response && response.data && response.data.content) {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: response.data.content.replace(/\n/g, '<br>') 
      });
      
      // 标记最后操作类型为建议
      aiLastAction.value = 'suggest';
      // 清除可应用内容，因为建议内容不需要应用
      aiGeneratedContent.value = null;
    }
  } catch (error) {
    console.error('获取改进建议出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，获取改进建议失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
      // 尝试渲染公式
      renderAIMessageMath();
    });
  }
};

// 测试AI API连接
const testAIApi = async () => {
  aiLoading.value = true;
  
  aiMessages.value.push({ 
    role: 'user', 
    content: '测试AI API连接...' 
  });
  
  // 滚动到底部
  nextTick(() => {
    if (aiContentRef.value) {
      aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
    }
  });
  
  try {
    const response = await testAIConnection();
    console.log('API测试响应:', response);
    
    if (response && response.data && response.data.status === 'success') {
      aiMessages.value.push({ 
        role: 'assistant', 
        content: `AI API连接测试成功！<br>
                 模型：${response.data.model}<br>
                 API地址：${response.data.apiUrl}<br>
                 响应信息：${response.data.response ? JSON.stringify(response.data.response).substring(0, 100) + '...' : '无响应信息'}`
      });
    } else {
      const error = response.data ? response.data.error : '未知错误';
      const model = response.data ? response.data.model : 'undefined';
      const apiUrl = response.data ? response.data.apiUrl : 'undefined';
      
      aiMessages.value.push({ 
        role: 'assistant', 
        content: `AI API连接测试失败：${error || '未知错误'}<br>
                 模型：${model}<br>
                 API地址：${apiUrl}`
      });
    }
  } catch (error) {
    console.error('测试AI API连接出错:', error);
    aiMessages.value.push({ 
      role: 'assistant', 
      content: '抱歉，测试AI API连接失败：' + (error.message || '未知错误') 
    });
  } finally {
    aiLoading.value = false;
    // 滚动到底部
    nextTick(() => {
      if (aiContentRef.value) {
        aiContentRef.value.scrollTop = aiContentRef.value.scrollHeight;
      }
    });
  }
};

// 应用AI生成的内容到表单
const applyAIGeneratedContent = () => {
  if (!aiGeneratedContent.value) {
    console.warn('没有可应用的AI生成内容');
    return;
  }
  
  try {
    console.log('准备应用AI生成内容:', aiGeneratedContent.value);
    
    // 应用题干
    if (aiGeneratedContent.value.questionContent) {
      // 清理前导文本和标记
      let cleanedContent = aiGeneratedContent.value.questionContent
        .replace(/^以下是一道关于[^"]*的[^"]*题：/i, '')
        .replace(/^这是一道关于[^"]*的[^"]*题：/i, '')
        .replace(/^下面是一道[^"]*题：/i, '')
        .replace(/^这是一道[^"]*题：/i, '')
        .replace(/^###\s*题目\s*/i, '') // 移除"### 题目"标记
        .replace(/^###\s*题干\s*/i, '') // 移除"### 题干"标记
        .replace(/\s*###\s*(?:答案|标准答案|参考答案)\s*$/i, '') // 移除末尾的答案标记
        .trim();
        
      console.log('已应用题干内容，清理前导文本后:', cleanedContent.substring(0, 50) + '...');
      
      // 确保题干内容不为空并正确设置
      if (cleanedContent && cleanedContent.length > 10) {
        questionForm.value.questionContent = cleanedContent;
        console.log('成功设置题干内容，长度:', questionForm.value.questionContent.length);
      } else if (aiGeneratedContent.value.content) {
        // 如果清理后的题干为空但有原始content，尝试提取标题部分
        let titleMatch = aiGeneratedContent.value.content.match(/###\s*题干\s*\n+([\s\S]+?)(?=\n+###|$)/i);
        if (!titleMatch) {
          titleMatch = aiGeneratedContent.value.content.match(/###\s*题目\s*\n+([\s\S]+?)(?=\n+###|$)/i);
        }
        
        if (titleMatch && titleMatch[1] && titleMatch[1].trim().length > 10) {
          let extractedTitle = titleMatch[1].trim()
            .replace(/^以下是一道.+的简答题：\s*/i, '') // 移除引导语
            .replace(/^这是一道.+的简答题：\s*/i, '') // 移除引导语
            .replace(/^###\s*题目\s*/i, '') // 移除可能嵌套的标题标记
            .replace(/^###\s*题干\s*/i, '') // 移除可能嵌套的标题标记
            .trim();
          
          questionForm.value.questionContent = extractedTitle;
          console.log('从content中提取题干/题目部分作为题干，长度:', questionForm.value.questionContent.length);
        } else {
          console.warn('无法提取有效题干，使用原始内容');
          questionForm.value.questionContent = aiGeneratedContent.value.questionContent;
        }
      }
    } else {
      console.warn('AI生成内容中没有题干');
    }
    
    // 应用答案
    let answerApplied = false;
    if (aiGeneratedContent.value.answer && aiGeneratedContent.value.answer.length > 5) {
      // 清理答案内容，移除可能的前缀
      let cleanedAnswer = aiGeneratedContent.value.answer
        .replace(/^(?:参考)?\s*答案[:：]\s*/i, '')
        .trim();
        
      console.log('应用答案，长度:', cleanedAnswer.length);
      questionForm.value.answer = cleanedAnswer;
      console.log('成功设置答案内容');
      answerApplied = true;
    }
    
    // 如果答案没有应用，但有content字段，尝试从content中提取
    if (!answerApplied && aiGeneratedContent.value.content) {
      // 首先尝试找参考答案部分
      let answerMatch = aiGeneratedContent.value.content.match(/###\s*(?:参考答案)\s*\n+([\s\S]+?)(?=\n+###|$)/i);
      if (!answerMatch) {
        // 然后尝试标准答案或普通答案部分
        answerMatch = aiGeneratedContent.value.content.match(/###\s*(?:答案|标准答案)\s*\n+([\s\S]+?)(?=\n+###|$)/i);
      }
      
      if (answerMatch && answerMatch[1] && answerMatch[1].trim().length > 5) {
        questionForm.value.answer = answerMatch[1].trim();
        console.log('从content中提取并设置答案，长度:', questionForm.value.answer.length);
        answerApplied = true;
      }
    }
    
    if (!answerApplied) {
      console.warn('AI生成内容中没有有效答案');
    }
    
    // 应用解析
    let analysisApplied = false;
    if (aiGeneratedContent.value.analysis && aiGeneratedContent.value.analysis.length > 5) {
      // 清理解析内容，移除可能的前缀
      let cleanedAnalysis = aiGeneratedContent.value.analysis
        .replace(/^解析[:：]\s*/i, '')
        .trim();
        
      console.log('应用解析，长度:', cleanedAnalysis.length);
      questionForm.value.analysis = cleanedAnalysis;
      console.log('成功设置解析内容');
      analysisApplied = true;
    }
    
    // 如果解析没有应用，但有content字段，尝试从content中提取
    if (!analysisApplied && aiGeneratedContent.value.content) {
      const analysisMatch = aiGeneratedContent.value.content.match(/###\s*(?:解析|分析|解答)\s*\n+([\s\S]+?)(?=$)/i);
      if (analysisMatch && analysisMatch[1] && analysisMatch[1].trim().length > 5) {
        questionForm.value.analysis = analysisMatch[1].trim();
        console.log('从content中提取并设置解析，长度:', questionForm.value.analysis.length);
        analysisApplied = true;
      }
    }
    
    if (!analysisApplied) {
      console.warn('AI生成内容中没有解析');
    }
    
    // 应用成功后给用户提示
    ElMessage.success('已成功应用AI生成的内容');
    
    // 滚动到表单顶部，以便用户查看生成的内容
    nextTick(() => {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  } catch (error) {
    console.error('应用AI内容出错:', error);
    ElMessage.error('应用AI内容失败: ' + (error.message || '未知错误'));
  }
};

// 从文本解析简答题
const parseQuestionFromText = (text) => {
  // 创建结果对象
  const questionData = {
    content: text, // 保存原始内容
    questionContent: '',
    answer: '',
    analysis: ''
  };
  
  try {
    console.log('开始解析简答题文本...');
    
    // 提取题干 - 优先使用标准格式 "### 题干"
    const titleSectionMatch = text.match(/###\s*题干\s*\n+([\s\S]+?)(?=\n+###|$)/i);
    if (titleSectionMatch && titleSectionMatch[1] && titleSectionMatch[1].trim().length > 5) {
      // 进一步清理题干，移除可能的前导文本
      let content = titleSectionMatch[1].trim()
        .replace(/^以下是一道.+的简答题：\s*/i, '') // 移除引导语
        .replace(/^这是一道.+的简答题：\s*/i, '') // 移除引导语
        .trim();
      
      questionData.questionContent = content;
      console.log('通过"### 题干"标记提取到题干，长度:', questionData.questionContent.length);
    } else {
      // 尝试从"### 题目"部分提取题干
      const titleMatch = text.match(/###\s*题目\s*\n+([\s\S]+?)(?=\n+###|$)/i);
      if (titleMatch && titleMatch[1] && titleMatch[1].trim().length > 5) {
        // 清理题目内容，移除可能的标记和前导文本
        let content = titleMatch[1].trim()
          .replace(/^以下是一道.+的简答题：\s*/i, '') // 移除引导语
          .replace(/^这是一道.+的简答题：\s*/i, '') // 移除引导语
          .trim();
          
        questionData.questionContent = content;
        console.log('通过"### 题目"标记提取到题干，长度:', questionData.questionContent.length);
      }
    }
    
    // 如果仍然没有提取到题干，尝试寻找题目与答案之间的内容
    if (!questionData.questionContent || questionData.questionContent.length < 10) {
      const fullContentMatch = text.match(/以下是一道关于[^"]*的[^"]*题：\s*\n+([\s\S]+?)(?=\n+###\s*(?:答案|标准答案|参考答案)|$)/i);
      if (fullContentMatch && fullContentMatch[1] && fullContentMatch[1].trim().length > 10) {
        questionData.questionContent = fullContentMatch[1].trim();
        console.log('从完整内容中提取题干，长度:', questionData.questionContent.length);
      }
    }
    
    // 最终处理题干：清除可能存在的标记
    if (questionData.questionContent) {
      questionData.questionContent = questionData.questionContent
        .replace(/^###\s*题目\s*/i, '')
        .replace(/^###\s*题干\s*/i, '')
        .trim();
      
      console.log('最终清理后的题干内容:', questionData.questionContent.substring(0, 50) + '...');
    }
    
    // 提取答案 - 尝试多种可能的格式
    // 1. 优先使用"### 参考答案"标记
    const referenceAnswerSection = text.match(/###\s*(?:参考答案)\s*\n+([\s\S]+?)(?=\n+###|$)/i);
    if (referenceAnswerSection && referenceAnswerSection[1] && referenceAnswerSection[1].trim().length > 5) {
      questionData.answer = referenceAnswerSection[1].trim();
      console.log('通过"### 参考答案"提取到答案，长度:', questionData.answer.length);
    } 
    // 2. 其次使用"### 答案"或"### 标准答案"标记
    else {
      const answerSection = text.match(/###\s*(?:答案|标准答案)\s*\n+([\s\S]+?)(?=\n+###|$)/i);
      if (answerSection && answerSection[1]) {
        questionData.answer = answerSection[1].trim();
        console.log('通过"### 答案"提取到答案，长度:', questionData.answer.length);
      } else {
        // 3. 尝试其他可能的答案格式
        const answerPatterns = [
          /(?:参考答案|标准答案|答案)[为是：:]\s*([\s\S]+?)(?=\n+###|(?:\n+解析)|\n+分析|$)/i,
          /(?:参考答案|标准答案|答案)[\s:：]*\n+([\s\S]+?)(?=\n+###|(?:\n+解析)|\n+分析|$)/i,
          /\n参考答案[:：]?\s*([\s\S]+?)(?=\n+###|(?:\n+解析)|\n+分析|$)/i,
          /\n答案[:：]?\s*([\s\S]+?)(?=\n+###|(?:\n+解析)|\n+分析|$)/i,
          /\n标准答案[:：]?\s*([\s\S]+?)(?=\n+###|(?:\n+解析)|\n+分析|$)/i
        ];
        
        for (const pattern of answerPatterns) {
          const match = text.match(pattern);
          if (match && match[1] && match[1].trim().length > 5) {
            questionData.answer = match[1].trim();
            console.log('通过替代模式提取到答案，长度:', questionData.answer.length);
            break;
          }
        }
      }
    }
    
    // 提取解析
    const analysisSection = text.match(/###\s*(?:解析|分析|解答)\s*\n+([\s\S]+?)(?=$)/i);
    if (analysisSection && analysisSection[1]) {
      questionData.analysis = analysisSection[1].trim();
      console.log('通过"### 解析"提取到解析，长度:', questionData.analysis.length);
    } else {
      // 备用解析提取方法
      const analysisPatterns = [
        /(?:解析|详细解析|分析|解答过程)[\s:：]*([\s\S]+)$/i,
        /\n解析[:：]?\s*([\s\S]+)$/i,
        /\n分析[:：]?\s*([\s\S]+)$/i
      ];
      
      for (const pattern of analysisPatterns) {
        const match = text.match(pattern);
        if (match && match[1] && match[1].length > 5) {
          questionData.analysis = match[1].trim();
          console.log('通过替代模式提取到解析，长度:', questionData.analysis.length);
          break;
        }
      }
    }
    
  } catch (error) {
    console.error('解析题目时发生错误:', error);
  }
  
  // 验证解析结果并输出详细日志
  const isValid = questionData.questionContent.length > 0 && questionData.answer.length > 0;
  
  console.log('题目解析结果：', {
    有题干: questionData.questionContent.length > 0,
    题干长度: questionData.questionContent.length,
    有答案: questionData.answer.length > 0,
    答案长度: questionData.answer.length,
    解析长度: questionData.analysis.length
  });
  
  if (isValid) {
    console.log('题目解析成功');
    return questionData;
  } else {
    console.warn('题目解析不完整，请检查生成的内容格式');
    return null;
  }
};

// 初始化
onMounted(() => {
  getChapterTreeselect();
  
  // 检查路由路径判断是否为编辑模式
  const questionId = route.params.id;
  if (questionId) {
    isEdit.value = true;
    getDetail(questionId);
  }
  
  // 预加载MathJax
  loadMathJax(); 
});
</script>

<style>
.ql-editor {
  min-height: 200px;
}

.ql-toolbar {
  background-color: #f8f8f8;
}

.ql-container {
  font-size: 14px;
}

.content-html img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}

.preview-container img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
</style>

<style scoped>
.app-container {
  padding: 20px;
}

.content-box {
  min-height: 80px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #fff;
  cursor: pointer;
  transition: border-color 0.2s;
}

.content-box:hover {
  border-color: #409eff;
}

.placeholder-text {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-group .el-button {
  margin: 0 10px;
}

.editor-container {
  width: 100%;
  margin-bottom: 20px;
}

.image-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

.preview-container {
  padding: 15px;
}

.preview-title {
  font-weight: bold;
  margin-top: 15px;
  margin-bottom: 5px;
}

.preview-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-answer {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-weight: bold;
}

.preview-container .MathJax {
  display: inline-block;
}

/* 渲染后的公式样式 */
.preview-content, .preview-option-content {
  overflow: visible;
  word-wrap: break-word;
  word-break: break-word;
}

/* 添加额外的样式确保KaTeX备选方案也能正确显示 */
.katex { 
  font-size: 1.1em !important;
}

/* AI助手对话框样式 */
.ai-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  gap: 15px;
}

.ai-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.ai-empty-message {
  color: #909399;
  text-align: center;
  padding: 20px;
}

.ai-empty-message ul {
  text-align: left;
  margin: 10px auto;
  max-width: 300px;
}

.ai-empty-message li {
  margin: 8px 0;
  color: #606266;
}

.ai-messages {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ai-message {
  padding: 12px 15px;
  border-radius: 8px;
  max-width: 85%;
  white-space: pre-wrap;
  word-break: break-word;
}

.ai-message.user {
  align-self: flex-end;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  color: #409eff;
}

.ai-message.assistant {
  align-self: flex-start;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  color: #67c23a;
}

.ai-message-content {
  line-height: 1.5;
}

.ai-function-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px 0;
}

.ai-function-buttons .el-button {
  flex: 1;
  min-width: 120px;
}

.ai-input-area {
  position: relative;
}

.ai-input-tip {
  position: absolute;
  right: 10px;
  bottom: -20px;
  font-size: 12px;
  color: #909399;
}

.ai-action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 25px;
}

/* 数学公式渲染相关样式 */
.ai-message .MathJax {
  display: inline-block !important;
  margin: 0 0.2em;
  vertical-align: middle;
  max-width: 100%;
  overflow-x: auto;
}

.ai-message .katex {
  font-size: 1.1em !important;
  max-width: 100%;
  overflow-x: auto;
}

.ai-message mjx-container {
  overflow-x: auto !important;
  max-width: 100%;
}

/* 确保图片正确显示 */
.ai-message img {
  max-width: 100%;
  height: auto;
  object-fit: contain;
  margin: 5px 0;
}

/* 代码块样式 */
.ai-message pre {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.ai-message code {
  font-family: Monaco, Consolas, Courier New, monospace;
}

/* 加载状态样式 */
.ai-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* 滚动条样式 */
.ai-content::-webkit-scrollbar {
  width: 6px;
}

.ai-content::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.ai-content::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>